package com.wolfking.jeesite.controller;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.wolfking.jeesite.config.SsoConfig;
import com.wolfking.jeesite.entity.Area;
import com.wolfking.jeesite.entity.Dict;
import com.wolfking.jeesite.service.AreaService;
import com.wolfking.jeesite.service.DictService;
import com.wolfking.jeesite.sign.Sign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 区域的controller
 * <p>
 *
 * @author wolfking@赵伟伟
 * @mail zww199009@163.com
 * @创作日期 2017年5月3日下午5:12:06
 * @版权 归wolfking所有
 */
@Slf4j
@Controller
@RequestMapping("/sys/area")
public class AreaController {

    @Autowired
    private AreaService areaService;

    @Autowired
    private DictService dictService;

    @Autowired
    private SsoConfig ssoConfig;

    @Sign(code = "sys:area:view")
    @RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    public String list(Model model) {
        List<Area> sourcelist = areaService.list();
        List<Area> list = Lists.newArrayList();
        sortList(list, sourcelist, 0, true);
        model.addAttribute("list", list);
        return "sys/area/list";
    }

    /**
     * 区域的编辑页面
     *
     * @param model
     * @param area
     * @return
     */
    @Sign(code = "sys:area:view")
    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String edit(Model model, Area area) {
        Area parent = new Area();
        if (Objects.nonNull(area.getId()))
            area = areaService.getById(area.getId());
        model.addAttribute("area", area);
        List<Area> list = areaService.list();
        model.addAttribute("list", list);

        List<Dict> types = dictService.getByType("sys_area_type");
        model.addAttribute("types", types);
        if (Objects.nonNull(area.getParentId()) && area.getParentId() > 0)
            parent = areaService.getById(area.getParentId());
        model.addAttribute("parent", parent);
        return "sys/area/edit";
    }

    /**
     * 区域的编辑页面
     *
     * @param model
     * @param area
     * @return
     */
    @Sign(code = "sys:area:view")
    @RequestMapping(value = "/copyEdit", method = RequestMethod.GET)
    public String copyEdit(Model model, Area area) {
        String view = edit(model, area);
        area = (Area) model.getAttribute("area");
        if (Objects.nonNull(area) && Objects.nonNull(area.getId())) {
            area.setName(area.getName() + "-2");
            if (Objects.nonNull(area.getSort())) {
                area.setSort(area.getSort() + 1);
            } else {
                area.setSort(0);
            }
            area.setId(null);
            area.setCreateTime(null);
            area.setUpdateTime(null);
            area.setVersion(0);
        }
        return view;
    }


    /**
     * 区域的保存或者修改
     *
     * @return
     */
    @Sign(code = "sys:area:edit")
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public String edits(Area area, RedirectAttributes redirectAttributes) {
        if (Objects.nonNull(area.getId())) {
            areaService.updateById(area);
            redirectAttributes.addFlashAttribute("message", "修改区域成功");
        } else {
            areaService.save(area);
            redirectAttributes.addFlashAttribute("message", "添加区域成功");
        }
        return ssoConfig.getRedirectWithPath("/sys/area/list");
    }

    /**
     * 删除区域
     *
     * @param id
     * @return
     */
    @Sign(code = "sys:area:edit")
    @RequestMapping(value = "/delete", method = RequestMethod.GET)
    public String delete(@RequestParam Integer id) {
        if (Objects.nonNull(id))
            areaService.deleteById(id);
        return ssoConfig.getRedirectWithPath("/sys/area/list");
    }

    /**
     * area的树数据
     *
     * @param extId
     * @return
     */
    @Sign
    @ResponseBody
    @RequestMapping(value = "/treeData")
    public List<Map<String, Object>> treeData(@RequestParam(required = false) Integer extId) {
        List<Map<String, Object>> mapList = Lists.newArrayList();
        List<Area> list = areaService.list();
        for (Area e : list) {
            if (!e.getId().equals(extId)) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("id", e.getId());
                map.put("pId", e.getParentId());
                map.put("name", e.getName());
                mapList.add(map);
            }
        }
        return mapList;
    }

    private void sortList(List<Area> list, List<Area> sourceList, Integer parentId, boolean cascade) {
        for (int i = 0; i < sourceList.size(); i++) {
            Area e = sourceList.get(i);
            if (parentId.equals(e.getParentId())) {
                list.add(e);
                if (cascade) {
                    // 判断是否还有子节点, 有则继续获取子节点
                    for (int j = 0; j < sourceList.size(); j++) {
                        Area child = sourceList.get(j);
                        if (e.getId().equals(child.getParentId())) {
                            sortList(list, sourceList, e.getId(), true);
                            break;
                        }
                    }
                }
            }
        }
    }

}
